package hibernatemock;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.GeneratedValue;
import javax.persistence.Transient;

public class MappedFieldsLookup {

	AnnotationHandler annotationHandler = new AnnotationHandler();
	//@Setter private List<Setup> setups; 2.0

	public Set<Field> lookupMappedFields(Class<?> clazz, boolean deep) {
		Set<Field> mappedFields = new HashSet<Field>();
		for (Field field : clazz.getDeclaredFields())
			if (!(Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())))
				if (!fieldOrGetterHasAnnotation(field, Transient.class) && !fieldOrGetterHasAnnotation(field, GeneratedValue.class))
					if (deep || annotationHandler.isRequired(field))
						// if (!isForcedNull(field)) 2.0
						mappedFields.add(field);
		return mappedFields;
	}

	// 2.0
	// private boolean isForcedNull(Field field) {
	// for (Setup setup : setups) {
	// if (field.getDeclaringClass() == setup.getClazzField()) {
	// field.setAccessible(true);
	// try {
	// if (field.get(setup.getInstance(null)) == null)
	// return true;
	// } catch (Exception e) {
	// throw new RuntimeException(e);
	// }
	// }
	// }
	// return false;
	// }

	private boolean fieldOrGetterHasAnnotation(Field field, Class<? extends Annotation> annotation) {
		if (annotationHandler.fieldOrGetterHasAnnotation(field, annotation) != null)
			return true;
		return false;
	}

}
